package com.example.mytestdemo.customviewbook.three

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import com.example.mytestdemo.R

class CustomView : View {
    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context)
    }

    private var mWidth = 0
    private var mHeight = 0
    private lateinit var mBmp: Bitmap
    private fun init(context: Context) {
        val drawable = context.resources.getDrawable(R.drawable.cat)
        mWidth = drawable.intrinsicWidth
        mHeight = drawable.intrinsicHeight
        mBmp = BitmapFactory.decodeResource(context.resources, R.drawable.cat)
        mWidth = mBmp.getWidth()
        mHeight = mBmp.getHeight()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //父布局为match_parent （EXACTLY）的话，子布局为wrap_content
        //得出模式MeasureSpec.getMode(widthMeasureSpec)为：AT_MOST
        //可以看书：3.1.2.1章的黄色标注出，以及当前小章图片：3-3
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (widthSize==0 || heightSize==0){
            setMeasuredDimension(mWidth, 100)
            return
        }
        if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, mHeight)
        } else if (widthMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, heightSize)
        } else if (heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSize, mHeight)
        } else {
            setMeasuredDimension(widthMeasureSpec, heightMeasureSpec)
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (mBmp == null) {
            return
        }
        canvas.drawBitmap(mBmp!!, 0f, 0f, null)
    }
}